package com.atguigu.tingshu.album.task;

import com.atguigu.tingshu.album.mapper.AlbumInfoMapper;
import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.model.album.AlbumInfo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author: jack
 * @date: 2025/10/9 17:15
 */
@Component
@Slf4j
public class BloomFilterTask {

    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    private AlbumInfoMapper albumInfoMapper;

    @Scheduled(cron = "0 0 1 * * ?")
    public void cleanBloomFilter() {
        //1.获取布隆过滤器的对象
        RBloomFilter<Long> bloomFilter = redissonClient.getBloomFilter(RedisConstant.ALBUM_BLOOM_FILTER);
        long count = bloomFilter.count();
        long expectedInsertions = bloomFilter.getExpectedInsertions();
        //2.判断布隆过滤器是否需要重建 需要重建
        if (count < expectedInsertions) {
            String name = bloomFilter.getName();
            RBloomFilter<Object> rBloomFilter = redissonClient.getBloomFilter(RedisConstant.ALBUM_BLOOM_FILTER + "new");
            List<AlbumInfo> albuminfoId = albumInfoMapper.selectList(
                    new LambdaQueryWrapper<AlbumInfo>().eq(AlbumInfo::getStatus, SystemConstant.ALBUM_STATUS_PASS)
                            .select(AlbumInfo::getId));
            for (AlbumInfo albumInfo : albuminfoId) {
                rBloomFilter.add(albumInfo.getId());
            }
            bloomFilter.delete();
            rBloomFilter.rename(name);
        } else {
            //需要扩容和重建
        }
    }
}
